<?php

namespace App\Jobs;

use App\Admin\Services\GoodService;
use App\Model\AmazonGood;
use App\Model\ExportGoodJobDetail;
use App\Model\Good;
use App\Model\ImportJob;
use App\Model\ImportJobFailed;
use Encore\Admin\Auth\Database\Administrator;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use GuzzleHttp\Promise;

class ImportAsinJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $row;


    protected $importJobId;


    protected $rowIndex;

    /**
     * Create a new job instance.
     * @param int $importJobId
     *
     * @param array $row
     */
    public function __construct(int $importJobId, int $rowIndex, array $row)
    {
        //
        $this->row = $row;
        $this->importJobId = $importJobId;

        $this->rowIndex = $rowIndex;
        $this->queue = 'import-asin';
    }

    /**
     * Execute the job.
     *
     * @return void|bool
     * @throws \Exception
     */
    public function handle()
    {

        if ($this->attempts() > 3) {
            return;
        }
        $importJob = ImportJob::query()
            ->where('status', '!=', 2)
            ->find($this->importJobId);

        if (!$importJob) {
            return;
        }

        $importJob->has_handle_count += 1;
        // 如果已经全部处理完则修改状态
        if ($importJob->has_handle_count == $importJob->total) {
            $importJob->status = 2;
        }

        // 如果当前job 是待导入则更新成 正在导入
        if ($importJob->status == 0) {
            $importJob->status = 1;
        }


        // 如果ASIN没有获取到，或者不是10位，就认为是无效数据
        if (strlen($this->row[4]) != 10) {
            $error = [
                'job_id' => $this->importJobId,
                'row' => $this->rowIndex,
                'type' => 0,
                'error_value' => $this->row[4]
            ];

            return $this->errorHandle($importJob, $error);
        }

        // sku 小于3 位也是无效数据
        if (strlen($this->row[0]) < 3) {
            $error = [
                'job_id' => $this->importJobId,
                'row' => $this->rowIndex,
                'type' => 1,
                'error_value' => $this->row[0]
            ];
            return $this->errorHandle($importJob, $error);
        }


        if (!empty($this->row[12])) {

            $supplier = Administrator::query()->where('username', GoodService::convertToUtf($this->row[12]))
                ->first();

            if (!$supplier || !$supplier->isRole('supplier')) {
                $error = [
                    'job_id' => $this->importJobId,
                    'row' => $this->rowIndex,
                    'type' => 3,
                    'error_value' => $this->row[12]
                ];
                return $this->errorHandle($importJob, $error);
            }
            $this->row['supplier_id'] = $supplier->id;
        }


        DB::beginTransaction();
        try {
            self::importAsin($this->row, $importJob->operator_id);
            $importJob->success_count += 1;
            $importJob->save();
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::info("导入asin失败：" . $exception->getMessage());
            $error = [
                'job_id' => $this->importJobId,
                'row' => $this->rowIndex,
                'type' => 2,
            ];
            return $this->errorHandle($importJob, $error);
        }
        DB::commit();
        return true;
    }


    /**
     * @desc 插入失败信息
     *
     * @param ImportJob $importJob
     * @param array $error
     *
     * @return bool
     * @author: 梅杰[meijie3169@dingtalk.com] at 2020-03-11 19:47:06
     */
    public function errorHandle(Model $importJob, array $error)
    {
        DB::beginTransaction();
        try {
            $importJob->save();
            ImportJobFailed::query()->insert($error);
        } catch (\Exception $exception) {
            DB::rollBack();
            return false;
        }
        DB::commit();
        return true;

    }

    /**
     * 导入asin 数据
     *
     * @param array $importData
     * @param int $operator
     * @throws \Exception
     */
    public static function importAsin(array $importData, int $operator)
    {
        // 判断数据库中是否存在amazon_good
        $amazon = AmazonGood::query()
            ->where('sku', $importData[0])
            ->first();

        if (!$amazon) {
            $amazon = new AmazonGood([
                'asin' => $importData[4],
                'sku' => $importData[0],
                'fnsku' => $importData[5]
            ]);
            $amazon->save();

            $goodData = self::initGood($importData);
            $goodData['amazon_goods_id'] = $amazon->id;
            $good = Good::query()->create($goodData);
        } else {
            // 存在则更新

            $good = Good::query()->where('amazon_goods_id', $amazon->id)
                ->first();

            if (!$good) {
                throw new \Exception('未查找到相关商品');
            }
            $good->fill(self::initGood($importData));

            $good->save();


            $amazon->asin = $importData[4];
            $amazon->sku = $importData[0];
            $amazon->fnsku = $importData[5];
            $amazon->save();

        }


        if (strlen($importData[8])) {
            $good->note()->create([
                'content' => ($importData[8]),
                'user_user_id' => $operator,
                'goods_id' => $good->id
            ]);
        }

    }


    /**
     * 初始化商品模型
     *
     * @param $import
     * @return array
     */
    private static function initGood(array $import)
    {
        $attributes = [];
        if (strlen($import[6])) {
            $attributes['goods_img_url'] = $import[6];
        }
        if (is_numeric($import[7])) {
            $attributes['price'] = $import[7];
        }
        if (strlen($import[1])) {
            $attributes['casku'] = $import[1];
        }
        if (strlen($import[2])) {
            $attributes['uksku'] = $import[2];
        }
        if (strlen($import[3])) {
            $attributes['jpsku'] = $import[3];
        }
        if (!empty($import[9])) {
            $attributes['web_sku'] = $import[9];
        }
        if (!empty($import[10])) {
            $attributes['number'] = $import[10];
        }
        if (!empty($import[11])) {
            $attributes['color'] = GoodService::convertToUtf($import[11]);
        }
        if (!empty($import[12])) {
            // 判断对应的供货商是否存在
            $attributes['supplier'] = GoodService::convertToUtf($import[12]);
        }
        if (!empty($import['supplier_id'])) {
            // 判断对应的供货商是否存在
            $attributes['supplier_id'] = $import['supplier_id'];
        }

        if (!empty($import[13])) {
            // 判断对应的供货商是否存在
            $attributes['ausku'] = $import[13];
        }
        $attributes['photo_img_id'] = null;

        return $attributes;
    }


}
